<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="入库日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="entryDate">
              <j-date placeholder="请选择入库日期" v-model="model.entryDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <j-vxe-table
      keep-source
      ref="workInboundRecordItem"
      :loading="workInboundRecordItemTable.loading"
      :columns="workInboundRecordItemTable.columns"
      :dataSource="workInboundRecordItemTable.dataSource"
      :maxHeight="300"
      :disabled="formDisabled"
      :rowNumber="true"
      :rowSelection="!formDisabled"
      :toolbar="true"
      :toolbarConfig="{
        slots: ['prefix', 'suffix'],
        btn: formDisabled ? [] : ['remove', 'clearSelection'],
      }"
      @valueChange="handleItemChange"
    >
      <template v-slot:batchNumber="{ row }">
        <a-select
          :disabled="formDisabled"
          v-model="row.batchNumber"
          mode="combobox"
          placeholder="请选择或输入批次号"
          :options="row.batchNumberOptions"
          show-search
          allow-clear
          style="width: 100%"
        >
          <a-select-option v-for="item in row.batchNumberOptions" :key="item.value" :value="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </template>
      <template v-slot:storageLocationName="{ row }">
        <a-input
          v-model="row.storageLocationName"
          placeholder="请选择储位"
          @click="chooseStorage(row)"
          :disabled="formDisabled"
        >
        </a-input>
        <storage-location
          ref="selectStorageList"
          @handleOk="storageOk"
          :warehouseCode="storageWarehouseCode"
        ></storage-location>
      </template>
    </j-vxe-table>
    <br />
    <div class="ant-descriptions-title">作业信息</div>
    <cargo-cascader
      style="margin-bottom: 10px"
      :max-level="2"
      load-children-on-select
      v-if="!formDisabled"
      @change="cargoSelectChange" />
    <j-vxe-table
      keep-source
      ref="cargoGroupMember"
      :loading="cargoGroupMemberTable.loading"
      :columns="cargoGroupMemberTable.columns"
      :dataSource="cargoGroupMemberTable.dataSource"
      :maxHeight="300"
      :rowNumber="true"
      :disabled="formDisabled"
      :rowSelection="!formDisabled"
      :toolbar="true"
      :toolbarConfig="{
            slots: ['prefix', 'suffix'],
            btn: ['remove', 'clearSelection'],
          }"
      @remove="handleCargoDelete"
    />
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import { JVXETypes } from '@comp/jeecg/JVxeTable'
import dayjs from 'dayjs'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
import utils from '@/utils/utils'
import StorageLocation from '../../inbound-order/StorageLocation.vue'
import CargoCascader from '@comp/warehouse/CargoCascader.vue'

export default {
  name: 'WorkInboundRecordForm',
  mixins: [JVxeTableModelMixin],
  components: {
    StorageLocation, 
    CargoCascader,
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      model: {
        // 作业入库
        entryType: 99,
        entryDate: dayjs().format('YYYY-MM-DD'),
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      warehouseCode: '',
      workshopPlanId: null,
      validatorRules: {},
      confirmLoading: false,
      workInboundRecordItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '计划单号',
            key: 'planNo',
            width: '110px',
          },
          {
            title: '订单编号',
            key: 'orderNo',
            width: '110px',
          },
          {
            title: '物料编码',
            key: 'materialCode',
            width: '110px',
          },
          {
            title: '物料名称',
            key: 'materialName',
            minWidth: '170px',
          },
          {
            title: '规格型号',
            key: 'specificationModel',
            width: '90px',
          },
          {
            title: '配方号',
            key: 'formulaNumber',
            width: '110px',
          },
          {
            title: '单位',
            key: 'unit_dictText',
            dictCode: 'ji_unit',
            width: '60px',
            align: 'center',
          },
          {
            title: '计划数量',
            key: 'planQuantity',
            width: '80px',
          },
          {
            title: '已入库数量',
            key: 'storedQuantity',
            width: '100px',
          },
          {
            title: '数量',
            key: 'quantity',
            type: JVXETypes.inputNumber,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '生产日期',
            key: 'productionDate',
            type: JVXETypes.date,
            width: '130px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '批次号',
            key: 'batchNumber',
            type: JVXETypes.slot,
            slotName: 'batchNumber',
            width: '150px',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '入库储位',
            key: 'storageLocationName',
            type: JVXETypes.slot,
            slotName: 'storageLocationName',
            width: '150px',
            defaultValue: '',
          },
        ],
      },
      // 作业信息
      cargoGroupMemberTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '姓名',
            key: 'memberName',
            type: JVXETypes.normal,
            width: '110px'
          },
          {
            title: '作业工种',
            key: 'jobType_dictText',
            type: JVXETypes.normal,
            minWidth: '180px'
          },
          {
            title: '作业吨数',
            key: 'jobWeight',
            type: JVXETypes.inputNumber,
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          }
        ]
      },
      url: {
        add: '/wms/inbound/inbound-record/add',
        workPlan: {
          list: '/wms/inbound/work-inbound-record/listWorkPlans',
        },
        outboundRecordCargoMember: {
          list: '/wms/outbound/outbound-record/queryOutboundRecordCargoMemberByMainId'
        },
        inboundDetail: '/wms/inbound/inbound-record/listAll',
      },
      // 新增用于存储当前操作的行
      currentRow: null, 
      storageWarehouseCode: null,
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {},
  methods: {
    edit(record) {
      if(this.formDisabled){
        this.editData(record)
      }else {
        this.workshopPlanId = record.id
        this.visible = true
        this.fetchData()
      }
    },
    // 选择储位
    chooseStorage(row) {
      this.storageWarehouseCode = row.warehouseCode;
      // 存储当前操作的行
      this.currentRow = row;  
      this.$nextTick(() => {
        this.$refs.selectStorageList.add()
      })
    },
    storageOk({ data }) {
      if (this.currentRow) {
        // 将选择的储位赋值到当前行
        this.currentRow.storageLocation = data.locationCode;
        this.currentRow.storageLocationName = data.locationName;
        // 重置当前行
        this.currentRow = null;
        this.storageWarehouseCode = null;
      }
    },
    fetchData() {
      getAction(this.url.workPlan.list, { workshopPlanId: this.workshopPlanId }).then((res) => {
        let { result } = res
        if (result && result.length) {
          result.forEach((item) => {
            item.productionDate = dayjs().format('YYYY-MM-DD')
            getAction(
              `/sys/dict/getDictItems/wms_work_inbound_label,batch_number,batch_number,plan_number='${item.planNo}' AND inbound_record_item_id is null`,
              {}
            ).then((res) => {
              item.batchNumberOptions = res.result
            })
          })
          this.workInboundRecordItemTable.dataSource = result
          this.warehouseCode = result[0].warehouseCode
          this.model.documentNumber = result[0].planNo
          this.model.orderNumber = result[0].orderNo
        }
      })
    },
    editData(record){
      getAction(this.url.inboundDetail, { id: record.id, inboundRecordItemId: record.inboundRecordItemId }).then((res) => {
        if (res.result && res.result.length) {
          let inboundDetail = res.result[0];
          this.model.entryDate = inboundDetail.entryDate
          inboundDetail.storageLocationName = inboundDetail.storageLocation_dictText
          getAction(this.url.workPlan.list, { planNo: record.documentNumber }).then((res) => {
            let { result } = res
            if (result && result.length) {
              result.forEach((item) => {
                if(inboundDetail.materialCode == item.materialCode 
                && inboundDetail.materialName == item.materialName 
                && inboundDetail.specificationModel == item.specificationModel){
                  inboundDetail.planNo = item.planNo
                  inboundDetail.orderNo = item.orderNo
                  inboundDetail.formulaNumber = item.formulaNumber
                  inboundDetail.planQuantity = item.planQuantity
                  inboundDetail.storedQuantity = item.storedQuantity
                  return
                }
              })
              this.workInboundRecordItemTable.dataSource.push(inboundDetail)
            }
          })
        }
      })
      this.cargoGroupMemberTable.dataSource = []
      let params = { id: record.id }
      this.requestSubTableData(this.url.outboundRecordCargoMember.list, params, this.cargoGroupMemberTable)
    },
    async submitForm() {
      const validate = await this.$refs.form.validate()
      if (!validate) {
        return
      }
      const errMap = await this.$refs.workInboundRecordItem.validateTable()
      if (errMap) {
        return
      }
      const formData = {
        entryDate: this.model.entryDate,
        entryType: this.model.entryType,
        orderNumber: this.model.orderNumber,
        documentNumber: this.model.documentNumber,
        warehouseCode: this.warehouseCode,
        inboundRecordItemList: this.workInboundRecordItemTable.dataSource.map((item) => {
          return {
            ...item,
            id: null,
          }
        }),
        outboundRecordCargoMemberList: this.cargoGroupMemberTable.dataSource.map(item => {
          return {
            ...item,
            cargoType: 2,
            id: null
          }
        }),
      }
      this.request(formData)
    },
    handleItemChange({ value, col, rowIndex }) {
      if (col.field === 'quantity' && value) {
        const item = this.workInboundRecordItemTable.dataSource[rowIndex]
        item.secondaryQuantity = utils.mul(value, item.unitConversionRate)
      }
    },
    cargoSelectChange({ value, list }) {
      if (list.length > 0) {
        this.cargoGroupMemberTable.dataSource = list.map(item => {
          return {
            memberName: item.memberName,
            jobType: item.jobType,
            jobType_dictText: item.jobType_dictText,
            memberId: item.id,
            groupId: item.groupId,
            teamId: value[0]
          }
        })
      }
    },
    handleCargoDelete({ deleteRows }) {
      this.cargoGroupMemberTable.dataSource = this.cargoGroupMemberTable.dataSource.filter(row =>
        !deleteRows.some(item => item.id === row.id)
      )
    },
  },
}
</script>
